package seata.bussiness.service;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import seata.bussiness.feign.OrderFeignClient;
import seata.bussiness.feign.StorageFeignClient;

import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class BusinessService {
    final StorageFeignClient storageFeignClient;
    final OrderFeignClient orderFeignClient;
    final JdbcTemplate jdbcTemplate;

    /**
     * 减库存，下订单
     */
    @GlobalTransactional
    public void purchase(String userId, String commodityCode, int orderCount) {
        log.info("Bussiness Service ... xid: " + RootContext.getXID());
        storageFeignClient.deduct(commodityCode, orderCount);

        orderFeignClient.create(userId, commodityCode, orderCount);

        if (!validData()) {
            throw new RuntimeException("账户或库存不足,执行回滚");
        }
    }

    public boolean validData() {
        Map<String, Object> accountMap = jdbcTemplate.queryForMap("select * from fescar_account_test.account_tbl where user_id='U100000'");
        if (Integer.parseInt(accountMap.get("money").toString()) < 0) {
            return false;
        }
        Map<String, Object> storageMap = jdbcTemplate.queryForMap("select * from fescar_storage_test.storage_tbl where commodity_code='C100000'");
        if (Integer.parseInt(storageMap.get("count").toString()) < 0) {
            return false;
        }
        return true;
    }
}